/* eslint-disable no-loop-func */
import { transArryToLinkList, transToArry, ListNode } from './util';

export function mergeArray(values: number[][]) {
    const resultArray: number[] = [];

    while((() => {
        values = values.filter(v => typeof v[0] === 'number');
        return values.length;
    })()) {
        const headArray = values.map(v => {
            return v[0];
        });
        const min = Math.min(...headArray);
        const minIndex = headArray.indexOf(min);
        resultArray.push(min);
        values[minIndex].shift();
    }
    return resultArray;
}

export default function mergeKLists(lists: Array<ListNode | null>): ListNode | null {
    const values = lists.map(l => {
        return transToArry(l);
    });

    const mergedArrayValues = mergeArray(values);

    return transArryToLinkList(mergedArrayValues);

};